#include "head.h"
#include <pthread.h>
#include <sys/epoll.h>


int main(int argc, char *argv[]){
    ARGS_CHECK(argc, 5);
    int sockfd = establishConnect(argv[1], argv[2]);
    threadPool_t threadPool;
    int threadCount = atoi(argv[3]);
    makeWorker(&threadPool, threadCount);
    int epfd = epoll_create(1);
    epollAdd(epfd, sockfd);
    struct epoll_event readyset[2];
    int agentSockfd;
    if(atoi(argv[4]) == 1){
        epoll_wait(epfd, readyset, 1, -1);
        agentSockfd = accept(sockfd, NULL, NULL);
        epollAdd(epfd, agentSockfd);
    }
    while(1){
        int readyNum = epoll_wait(epfd, readyset, 2, -1);
        for(int i = 0; i < readyNum; ++i){
            if(readyset[i].data.fd == sockfd){
                int clientSockfd = accept(sockfd, NULL, NULL);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.workQueue, clientSockfd);
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else{
                train_t train;
                bzero(&train, sizeof(train_t));
                int ret = recvOrderTrain(agentSockfd, &train);
                if(ret == -1){
                    close(sockfd);
                    break;
                }
                char MD5[1024] = {0};
                int fd = open(MD5, O_RDONLY);
                int fileSize = lseek(fd, 0, SEEK_END);
                char buf[16] = {0};
                sprintf(buf, "%d", fileSize);
                TLVResponse(agentSockfd, buf, FILE_LEN);
                close(fd);
            }
        }
    }
    return 0;
}

